package com.ctbu.score.controller;

import com.ctbu.score.domain.Classes;
import com.ctbu.score.domain.MyError;
import com.ctbu.score.domain.Score;
import com.ctbu.score.domain.Student;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ctbu.score.service.ClassService;
import com.ctbu.score.service.ScoreService;
import com.ctbu.score.service.StudentService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 学生控制器类
 **/
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private ClassService classService;

    @Autowired
    private ScoreService scoreService;

    /**
     * 处理学生登录请求。
     * @param username 用户名
     * @param password 密码
     * @param map 存储信息的 Map
     * @param session HttpSession 对象
     * @return 登录成功重定向到学生主页，失败返回登录页面
     */
    @PostMapping(value = "/stu/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, Map<String,Object> map, HttpSession session)
    {
        Student stu = studentService.login(username,password);
        if(stu != null)
        {
            session.setAttribute("loginUser",username);
            return "redirect:/stumain.html";
        }
        else
        {
            map.put("msg","用户名或密码错误");
            return  "login";
        }
    }

    /**
     * 返回学生主页。
     * @return 学生主页
     */
    @GetMapping(value = "/stu/toindex")
    public String toindex(){
        return "redirect:/stumain.html";
    }


    /**
     * 返回学生信息修改页面。
     * @param httpSession HttpSession 对象
     * @param model Model 对象
     * @return 学生信息修改页面
     */
    @GetMapping(value = "/stu/toUpdateMsgPage")
    public String toUpdateMsgPage(HttpSession httpSession, Model model)
    {
        Student stu = studentService.selectById((String) httpSession.getAttribute("loginUser"));
        List<Classes> classes = classService.getAllClass();
        model.addAttribute("stu",stu);
        model.addAttribute("classes",classes);
        return "stu/updateStu";
    }

    /**
     * 更新学生信息操作。
     * @param student 需要更新的学生 Student 对象
     * @param bindingResult 绑定结果
     * @param model Model 对象
     * @param httpSession HttpSession 对象
     * @return 更新成功重定向到更新成功页面，失败返回学生信息修改页面
     */
    @PutMapping(value = "/stu/updateStuMsg")
    public String updateStuMsg(@Valid Student student, BindingResult bindingResult, Model model, HttpSession httpSession)
    {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<MyError> errmsg = new ArrayList<>();
        List<Classes> classes = classService.getAllClass();
        if(allErrors.size() == 0)
        {
            Student studentInit = studentService.selectById((String) httpSession.getAttribute("loginUser"));
            student.setStuId(studentInit.getStuId());
            student.setStuName(studentInit.getStuName());
            student.setStuClass(studentInit.getStuClass());
            student.setStuSex(studentInit.getStuSex());

            studentService.deleStu(studentInit.getStuId());
            studentService.addStudentHavePass(student);
            return "redirect:/updateSucc.html";
        }
        else
        {
            for (ObjectError error : allErrors)
            {
                errmsg.add(new MyError(error.getDefaultMessage()));
            }
            model.addAttribute("errors", errmsg);
            model.addAttribute("stu", student);
            model.addAttribute("classes", classes);
            return "stu/updateStu";
        }
    }

    /**
     * 返回学生成绩首页。
     * @param pn 当前页码
     * @param model Model 对象
     * @param httpSession HttpSession 对象
     * @return 学生成绩列表页面
     */
    @GetMapping(value = "/stu/toresdmin/{pn}")
    public String toresdmin(@PathVariable("pn") Integer pn, Model model, HttpSession httpSession)
    {
        PageHelper.startPage(pn, 9);
        List<Score> scores =scoreService.selectByStuId((String) httpSession.getAttribute("loginUser"));
        PageInfo<Score> page = new PageInfo<>(scores, 5);
        model.addAttribute("pageInfo", page);
        return "stu/resultlist";
    }

    /**
     * 根据学期查询学生成绩。
     * @param pn 当前页码
     * @param resTerm 学期
     * @param model Model 对象
     * @param httpSession HttpSession 对象
     * @return 指定学期的学生成绩列表页面
     */
    @GetMapping(value = "/stu/selectResByTerm/{pn}")
    public String selectResByTerm(@PathVariable("pn") Integer pn, @Param("resTerm") String resTerm, Model model, HttpSession httpSession)
    {
        PageHelper.startPage(pn, 9);
        List<Score> scores = scoreService.selectByStuIdAndScoTerm((String) httpSession.getAttribute("loginUser"), resTerm);
        PageInfo<Score> page = new PageInfo<>(scores, 5);
        model.addAttribute("pageInfo", page);
        model.addAttribute("resTerm", resTerm);
        return "stu/reslistbyterm";
    }
}
